package com.clw.template.config;

import com.clw.template.util.ApplicationException;
import com.clw.template.util.CommonResult;
import com.clw.template.util.ResultCode;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.List;
import java.util.Set;


@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Object applicationHandler(MethodArgumentNotValidException e) {
        List<FieldError> bindingResult = e.getBindingResult().getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : bindingResult) {
            sb.append(fieldError.getDefaultMessage()+";  \r\n");

        }
        if (sb.toString().length() > 0) {
            System.out.println(sb.toString());
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), sb.toString());
        }
        return CommonResult.failed(ResultCode.VALIDATE_FAILED);
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Object applicationHandler(AccessDeniedException e){
        return CommonResult.forbidden(e.getMessage());
    }
    @ExceptionHandler(ApplicationException.class)
    @ResponseBody
    public Object applicationHandler(ApplicationException e){
        return CommonResult.failed(e.getCode(),e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object seriousHandler(Exception e){
        e.printStackTrace();
        LOGGER.info(e.toString());
        return CommonResult.failed();
    }

}
